<?php
class UserMessage extends Zend_Db_Table_Abstract {
	
	const MESSAGE_ID = "message_id";
	const TARGET_USER_ID = "target_user_id";
	const STATUS = "status";
	
	protected $_primary = "id";
	protected $_name = "user_message";
	
	protected $_referenceMap = array (
    'TargetUser' => array (
        'columns' => 'target_user_id', 
        'refTableClass' => 'User', 
        'refColumns' => 'id' 
    ),
    'Message' => array (
        'columns' => 'message_id', 
        'refTableClass' => 'Message', 
        'refColumns' => 'id' 
    )
    );
    
    /**
     * Find user message by id.
     * 
     * @param $id
     * @return return user message
     */
    public function findById($id) {
    	return $this->find($id)->current();
    }
    
    /**
     * Add new user message.
     * 
     * @param $message
     * @param $targetUser
     * @param $subject
     * @param $type
     * @param $created
     */
    public function addUserMessage($data) {
    	return $this->insert($data);
    }
    
    /**
     * Return message.
     * 
     * @param $userMessage
     */
    public static function getMessage($userMessage) {
    	return $userMessage->findParentRow('Message');
    }
    
    /**
     * Return target user of message.
     * 
     * @param $userMessage
     */
    public static function getTargetUser($userMessage) {
        return $userMessage->findParentRow('User', 'TargetUser');
    }

    /**
     * Update user message status, only update those sender is not equal to the loggedInUser.
     * 
     * @param $message
     * @param $loggedInUser
     */
    public static function updateUserMessagesStatus($message, $loggedInUser) {
        $userMessage = Message::getUserMessage($message);
        if (UserMessage::getMessage($userMessage)->user_id != $loggedInUser->id 
            || (UserMessage::getMessage($userMessage)->user_id == UserMessage::getTargetUser($userMessage)->id && UserMessage::getMessage($userMessage)->user_id == $loggedInUser->id)) {
        	$userMessage->status = UserMessageStatus::READ;
        	$userMessage->save();
        }
        $replyMessages = Message::getReplyMessages($message);
        foreach ($replyMessages as $replyMessage) {
        	$userMessage = Message::getUserMessage($replyMessage);
        	if (UserMessage::getMessage($userMessage)->user_id != $loggedInUser->id 
            || (UserMessage::getMessage($userMessage)->user_id == UserMessage::getTargetUser($userMessage)->id && UserMessage::getMessage($userMessage)->user_id == $loggedInUser->id)) {
	        	$userMessage->status = UserMessageStatus::READ;
	        	$userMessage->save();
            }
        }
    }
}
?>